package com.ccys.app.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.app.childRegistrationScreen.CheckChildInfoDto;
import com.ccys.db.dto.app.childRegistrationScreen.RegisterChildDto;
import com.ccys.db.entity.TblMember;
import com.ccys.db.entity.TblMemberFamily;
import com.ccys.db.mapper.TblMemberFamilyMapper;
import com.ccys.db.mapper.TblMemberMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author：XLY
 * @Date：2024/1/31 0031
 */

@RestController
@RequestMapping("/childRegistrationScreen")
@Api(tags = "Child Registration Screen")
public class ChildRegistrationScreenController {


    @Resource
    private TblMemberMapper memberMapper;

    @Resource
    private TblMemberFamilyMapper familyMapper;

    @ApiOperation("Child Registration Screen/1")
    @PostMapping("CheckChildInfo")
    public ResponseResultApp CheckChildInfo(CheckChildInfoDto dto) {
        //The identification number you have entered is already in use. Please try again.
        //Your identification number must be at least 6 characters.
        String nric_fin = dto.getNric_fin();
        if (StringUtils.isEmpty(nric_fin) || nric_fin.length() < 6) {
            return ResponseResultApp.error("Your identification number must be at least 6 characters");
        }

        int count = checkChildNric(nric_fin);
        if (count == 0) {
            return ResponseResultApp.success();
        } else {
            return ResponseResultApp.error("The identification number you have entered is already in use. Please try again.");
        }

    }

    private int checkChildNric(String nric_fin) {
        Example example = new Example(TblMember.class);
        example.createCriteria().andEqualTo("nricFin", nric_fin);
        int count = memberMapper.selectCountByExample(example);
        return count;
    }


    @ApiOperation("Child Registration Screen/2")
    @PostMapping("RegisterChild")
    @Transactional
    public ResponseResultApp registerChild(RegisterChildDto dto) {

        String type_id = dto.getType_id();
        String front_identification_card_photo = dto.getFront_identification_card_photo();
        String back_identification_card_photo = dto.getBack_identification_card_photo();
        String passport_photo = dto.getPassport_photo();
        String birth_certificate_photo = dto.getBirth_certificate_photo();
        String child_photo = dto.getChild_photo();
        String nric_fin = dto.getNric_fin();
        if ("nric_fin".equals(type_id) && StringUtils.isNotEmpty(front_identification_card_photo)) {

            return ResponseResultApp.error("The front_identification_card_photo field is required.");

        } else if ("nric_fin".equals(type_id) && StringUtils.isNotEmpty(back_identification_card_photo)) {

            return ResponseResultApp.error("The back_identification_card_photo field is required.");

        } else if ("passport".equals(type_id) && StringUtils.isNotEmpty(passport_photo)) {

            return ResponseResultApp.error("The passport_photo field is required.");

        } else if ("birth_certificate".equals(type_id) && StringUtils.isNotEmpty(birth_certificate_photo)) {

            return ResponseResultApp.error("The birth_certificate_photo field is required.");

        } else if ("child_photo".equals(type_id) && StringUtils.isNotEmpty(child_photo)) {

            return ResponseResultApp.error("The child_photo field is required.");
        }
        int min_age = 16;
        String date_of_birth = dto.getDate_of_birth();
        DateTime date_of_birth_date = DateUtil.parse(date_of_birth);
        int age = (int) DateUtil.betweenYear(date_of_birth_date, new Date(), false);
        if (age > min_age) {
            return ResponseResultApp.error("Age should be greater than 0 and less than 16 years. Please enter a valid date of birth.");
        }
        //根据这个nric看这个小孩是否存在了
        int count = checkChildNric(nric_fin);
        if (count > 0) {
            return ResponseResultApp.error("The identification number you have entered is already in use. Please try again.");
        }
        //// TODO: 2024/1/31 0031 timezone
        // 保存小孩
        TblMember child = new TblMember();
        //1:NRIC_FIN 2:Passport 3:Birth_certificate 4:Driving_license 5:Child_photo
        //child.setType();
        child.setFirstName(dto.getFirst_name());
        child.setLastName(dto.getLast_name());
        child.setNricFin(dto.getNric_fin());
        child.setGender("male".equals(dto.getGender())?1:"female".equals(dto.getGender())?0:-1);
        //父账号关系 1parent 2guardian 3mother 4father
        Integer relationship = 1;
        switch (dto.getRelationship()){
            case "guardian":
                relationship = 2;
                break;
            case "mother":
                relationship = 3;
                break;
            case "father":
                relationship = 4;
                break;
            default:
                break;
        }
        child.setRelationship(relationship);
        String curLoginUserId = UserUtil.getCurLoginUserId();
        child.setParentId(curLoginUserId);
        child.setFrontIdentificationPhoto(front_identification_card_photo);
        child.setBackIdentificationPhoto(back_identification_card_photo);
        if(StringUtils.isNotBlank(passport_photo)){
            child.setFrontIdentificationPhoto(passport_photo);
//        child.setPassport(passport_photo);
        }
        if(StringUtils.isNotBlank(birth_certificate_photo)){
            child.setFrontIdentificationPhoto(birth_certificate_photo);
//            child.setBirthCertificate(birth_certificate_photo);
        }
        memberMapper.insert(child);
        // 保存小孩到family
        TblMemberFamily family = new TblMemberFamily();
        family.setMemberId(curLoginUserId);
        family.setDependantId(child.getId());
        family.setStatus(1);
        family.setCode(nric_fin);
        family.setRelationship(relationship);
        family.setMemberIdSendInvitation(curLoginUserId);
        familyMapper.insert(family);
        // TODO: 2024/1/31 0031 开线程 去 “addAllChildBenefitsIntoChild”
        // 再上传一遍照片？(照片是传的2进制数组，需要后台调用s3上传，然后呢后台生成一个随机数加前缀存到数据库)
        // TODO: 2024/1/31 0031   再查询一遍memberinfof返回？
        return ResponseResultApp.success();
    }




}
